﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using Caliburn;
using Caliburn.Services;
using NServiceBus.Config;
using NServiceBus.Management.Config;
using NServiceBus.Management.EndpointExplorer;
using NServiceBus.Management.EndpointExplorer.Config;
using NServiceBus.Management.MessageHandlers;
using NServiceBus.Management.Messages.Status;
using NServiceBus.Unicast.Config;
using NServiceBus.Unicast.Subscriptions.Msmq.Config;
using NServiceBus.Unicast.Transport.Msmq.Config;
using ObjectBuilder;
using ObjectBuilder.CastleFramework;

namespace NServiceBus.Management.Shell.Application
{
    public class App : System.Windows.Application
    {
        public static IBus bus;

        private static EndpointManager monitor;
        private static CustomConfiguration configuration;
        private static IBuilder builder;
        
        public App()
        {
            configuration = new CustomConfiguration();
            CaliburnApplication.Start(configuration);

            builder = new Builder(configuration.Container.Kernel);

        }

        protected override void OnStartup(StartupEventArgs e)
        {
            Configure.With(builder).SagasAndMessageHandlersIn(Assembly.GetExecutingAssembly(), 
                                                              typeof(StatusEventHandler).Assembly,
                                                              typeof(EndpointMessageHandler).Assembly);
            new ConfigMsmqSubscriptionStorage(builder);

            new ConfigMsmqTransport(builder)
                .IsTransactional(true)
                .PurgeOnStartup(true)
                .UseXmlSerialization(false);

            new ConfigUnicastBus(builder)
                .ImpersonateSender(false)
                .SetMessageHandlersFromAssembliesInOrder(Assembly.GetExecutingAssembly(),
                                                         typeof(StatusEventHandler).Assembly,
                                                         typeof(EndpointMessageHandler).Assembly);

            new ConfigManagement(builder);

            new ConfigEndpointExplorer(builder)
                .SetMessagesFromAssemblies(typeof (StatusMessage).Assembly);

            bus = builder.Build<IBus>();

            bus.Start();

            bus.Subscribe(typeof(StatusEvent));

            monitor = builder.Build<EndpointManager>();
            monitor.Start();

            MainWindow = new ShellWindow();
            MainWindow.Show();

            //DI.Resolve<IModuleManager>().RefreshModules();

            base.OnStartup(e);
        }

        protected override void OnExit(ExitEventArgs e)
        {
            bus.Unsubscribe(typeof(StatusEvent));
            monitor.Stop();
        }
    }
}
